

Panels.Main.TileAddition = function()
{
  var tile = Global.CurrentTile;
  var x = tile.x;
  var y = tile.y;
  var id = tile.id;
  var type = tile.type;

  if (type & TileType.Solid_Energy || type & TileType.Exotic_Matter)
  {
    Global.CurrentTile.cell.addEvent("contextmenu", function() { return false; });
  }
  else
  {
    Global.CurrentTile.cell.set("id", "nav_" + id)
      .addEvent("mouseup", (function(event) { Panels.Main.HandleTileClick(event, this.x, this.y, this.id, this.type); return false; }).bind({ x: x, y: y, id: id, type: type }))
      .addEvent("contextmenu", (function(event) { Panels.Main.HandleTileClick(event, this.x, this.y, this.id, this.type); return false; }).bind({ x: x, y: y, id: id, type: type }));
  }
}

EventSink.addEvent("TileCreated", Panels.Main.TileAddition);

Panels.Main.HandleTileClick = function(event, x, y, id, type)
{
  var el = $("nav_" + id);
  var pos = el.getPosition();
  var dim = el.getDimensions();
  var mousePosition = new Event(event).page;

  var dataString = x + ", " + y + ", " + id + ", " + type;

  if (event.rightClick)
  {
    RightClickMenu.setPosition({ x: mousePosition.x + 2, y: mousePosition.y + 2 });
    LeftClickMenu.setPosition({ x: pos.x + dim.x + 2, y: pos.y });
    HideMenus();

    var object = Utility.Object.GetType(id);

    if (object == eNull)
    {
      var w = "<div class='rightClickMenu'><ul>"
            + "<li><a href='javascript:void(0);' onclick='Panels.Main.ShowCreateMenu(eBuilding, " + dataString + ");'>Create Building</a></li>"
            + (type & TileType.Space ? "<li><a href='javascript:void(0);' onclick='Panels.Main.ShowCreateMenu(ePlanet, " + dataString + ");'>Create Planet</a></li>" : "")
            + (!(type & TileType.Asteroids || type & TileType.Viral_Cloud) ? "<li><a href='javascript:void();' onclick='Panels.Main.ShowCreateMenu(eStarbase, " + dataString + ");'>Create Starbase</a></li>" : "")
            + "<li><a href='javascript:void(0);' onclick='Panels.Main.ShowCreateMenu(eBackground, " + dataString + ");'>Create Background</a></li>"
            + "<li><a href='javascript:void(0);' onclick='HideMenus();'>Cancel</a></li>"
            + "</ul></div>";
    }

    else
    {
      var w = "<div class='rightClickMenu'><ul>"
            + "<li><a href='javascript:void(0);' onclick='Panels.Main.ShowInfo(\"" + object + "\", " + id + ");'>View " + object + " Info</a></li>"
            + "<li><a href='javascript:void(0);' onclick='Panels.Main.DeleteObject(\"" + object + "\", " + id + ");'>Delete " + object + "</a></li>"
            + "<li><a href='javascript:void(0);' onclick='HideMenus();'>Cancel</a></li>"
            + "</ul></div>";
    }

    RightClickMenu.set("html", w);
  }
  else
  {
    HideMenus();

    if (Utility.Tile.IsSelected(id))
      Utility.Tile.DeSelect(id);

    else
      Utility.Tile.Select(id);
  }
}